package ru.aptu.gsp_banking.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.aptu.gsp_banking.domain.Account;
import ru.aptu.gsp_banking.domain.Currency;
import ru.aptu.gsp_banking.domain.MoneyTransfer;
import ru.aptu.gsp_banking.service.AccountService;
import ru.aptu.gsp_banking.service.CurrencyService;
import ru.aptu.gsp_banking.service.MoneyTransferService;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 1/20/12
 * Time: 3:25 PM
 */

@Controller
public class MoneyTransferController {
    
    @Autowired
    private AccountService accountService;

    @Autowired
    private CurrencyService currencyService;

    @Autowired
    private MoneyTransferService moneyTransferService;

    private boolean posted = false;

    @ModelAttribute("accounts")
    public List<Account> listAccounts(Principal principal) {
        final String currentUser = principal.getName();
        return accountService.listAccount(currentUser);
    }

    @ModelAttribute("currencies")
    public List<Currency> listCurrencies() {
        return currencyService.listCurrency();
    }

    @RequestMapping(value = "/money_transfers", method = RequestMethod.POST)
    public String moneyTransfersPost() {
        posted = true;
        return "redirect:money_transfers";
    }

    @RequestMapping(value = "/money_transfers", method = RequestMethod.GET)
    public String moneyTransfersGet(Map<String, Object> map, Principal principal) {
        if (!posted) {
            return "redirect:logout";
        }
        posted = false;

        MoneyTransfer moneyTransfer = new MoneyTransfer();
        map.put("moneyTransfer", moneyTransfer);
        return "money_transfers";
    }

    @RequestMapping(value = "/submit_transfer", method = RequestMethod.POST)
    public String addCard(@ModelAttribute("moneyTransfer") MoneyTransfer moneyTransfer, BindingResult result) {
        boolean transferResult = moneyTransferService.submitMoneyTransfer(moneyTransfer);
        if (transferResult)
            return "redirect:/request_success";
        else
            return "redirect:/request_fail";
    }

}
